<?php
/** 
 * 新后台登录相关
 *
 * @author   xg
 * @date     2019-09-12
 */

namespace app\index\controller;

use other\BaseRedis;
use think\facade\Env;
use app\base\controller\Backend;
use app\index\model\UserModel;
use app\home\model\AuthRuleModel;
use service\UserTokenService;

class Login extends Backend
{
    
    protected $noNeedLogin = [
        'index/login/login',
        'index/login/sendcode',
    ];

    protected $noNeedRight = [
        'index/login/login',
        'index/login/sendcode',
    ];

    /**
     * 默认方法
     */
    public function index()
    {
        $this->error();
    }

    /**
     * 后台登录
     * @param number  $phone    手机号
     * @param number  $code     验证码
     * @return array
     */
    public function login()
    {
        $rule = [
            'phone' => 'require|number',
            'code'  => 'require|number',
        ];

        $msg = [
            'phone.require' => '手机号不能为空',
            'phone.number'  => '手机号不正确',
            'code.require'  => '验证码不能为空',
            'code.number'   => '验证码不正确',
        ];

        $data = $this->paramCheck($rule, $msg, $this->request->param());

        if (!is_array($data)) {
            $this->error($data);
        }

        $res = $this->checkCode(
            $this->request->param('phone'), $this->request->param('code')
        );

        if (!$res) {
            $this->error("验证码错误");
        }

        $user_model     = new UserModel();
        $rule_model     = new AuthRuleModel();
        $token_service  = new UserTokenService();
        $user_data      = $user_model->checkLogin($this->request->param('phone'));

        if (empty($user_data)) {
            $this->error("登录失败");
        }

        $token_decode = $token_service->createToken($user_data['user_id']);
        $this->setToken($token_decode);

        $result['user_id'] = $user_data['user_id'];

        if (empty($user_data['user_nickname'])) {
            $result['account'] = $user_data['user_tel'];
        } else {
            $result['account'] = $user_data['user_nickname'];
        }

        if (empty($user_data['user_headimg'])) {
            $result['avatar'] = 'https://image.jiunidu.com/web/login.png';
        } else {
            $result['avatar'] = $user_data['user_headimg'];
        }

        $result['menu'] = $rule_model->getMenu();
        
        $this->success('登录成功', $result); 
    }

    /**
     * 后台登出
     * @param string    $token  令牌
     * @return array
     */
    public function logout()
    {
        $this->success('退出成功');
    }

    /**
     * 发送验证码
     * @param number  $phone    手机号
     * @return array
     */
    public function sendCode()
    {
        $rule = [
            'phone' => 'require|number',
        ];

        $msg = [
            'phone.require' => '手机号不能为空',
            'phone.number'  => '手机号不正确',
        ];

        $data = $this->paramCheck($rule, $msg, $this->request->param());

        if (!is_array($data)) {
            $this->error($data);
        }
        
        $user_model = new UserModel();

        $result = $user_model->checkLogin($this->request->param('phone'));

        if (!$result) {
            $this->error('该号码没有登录后台权限');
        }

        $icode = $this->createCode($this->request->param('phone'));

        if (empty($icode)) {
            $this->error('验证码添加失败');
        }

        $code_str   = '{"code":'.$icode.'}';
        $yesno      = send_sms('SMS_159580106', $this->request->param('phone'), $code_str);

        if ($yesno) {
            $this->success('发送验证码成功');  
        }

        $this->error('发送验证码失败');
    }

    /**
     * 检查验证码
     * @param number  $phone    手机号
     * @param number  $code     验证码
     * @return boole
     */
    private function checkCode($phone, $icode)
    {
        $code = Env::get('admin_login_sms.code');

        if (isset($code) && $code == $icode && $phone == '18607921775') {
            return true;
        }

        $yesno_icode = $this->validateCode($phone, $icode);

        if (!$yesno_icode) {
           return false;
        }

        return true;
    }

    /**
     * 生成验证码
     * @param number  $phone    手机号
     * @return number
     */
    private function createCode($phone)
    {
        try {
            $redis = new BaseRedis();

            if ($redis->has("user_icode:".$phone.":backend_login")) {
                return $redis->get("user_icode:".$phone.":backend_login");
            }

            $i_code = rand('100000','999999');
            $redis->set("user_icode:".$phone.":backend_login", $i_code, 100);
        }
        catch (\Exception $e) {}

        return  $i_code ?? '';
    }

    /**
     * 校验验证码
     * @param number  $phone    手机号
     * @param number  $code     验证码
     * @return boole
     */
    private function validateCode($phone, $code)
    {
        try {
            $redis = new BaseRedis();

            if ($redis->has("user_icode:".$phone.":backend_login")) {
                $data = $redis->get("user_icode:".$phone.":backend_login");

                if ($data == $code) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        catch (\Exception $e) {}
    }

}